package com.orangelife.mobile.goodsOrder.biz;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.util.TimeUtil;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.util.LogE;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.goodsOrder.activity.BackGoodActivity;
import com.orangelife.mobile.pay.activity.UsersPaidActivity;
import com.orangelife.mobile.pay.interfaze.IOuttradenoCallBack;
import com.orangelife.mobile.pay.biz.PayManageImpl;
import com.orangelife.mobile.pay.biz.PaymentModule;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by YangWei
 * on 2016/1/12.
 */
public class OrderBiz {
    public static final int DETAIL_LIST = 1;
    public static final int APILAY_KEY = 3;
    public static final int APILAY_PAID = 4;
    public static final int READ_FLAG = 5;
    public static final int PAID_STATE = 6;
    public static final int CANCEL_JUMP = 9;
    public static final int CONFIRM_GOOD = 10;

    /** 订单类型和支付方式映射关系 */
    public static String getPaidTypeFromOrderType(String orderType) {
        String paidType = "";
        if ("1".equals(orderType)) {
            paidType = PaymentModule.mode[0];
        } else if ("3".equals(orderType)) {
            paidType = PaymentModule.mode[2];
        } else if ("14".equals(orderType) || "19".equals(orderType)) {//19为社区活动里的话费充值
            paidType = PaymentModule.mode[1];
        } else if ("17".equals(orderType)) {
            paidType = PaymentModule.mode[12];
        } else if (PaymentModule.COMMUNITY_ACTIVITY.equals(orderType)) {
            paidType = PaymentModule.COMMUNITY_ACTIVITY;
        }
        return paidType;
    }

    /**
     * 退回商品
     */
    public static void backGoods(String applicationID, Activity activity) {
        Bundle bundle = new Bundle();
        bundle.putString("applicationID", applicationID);
        IntentHelper.getInstances().bundleWithBundleForResult(activity, BackGoodActivity.class, bundle, CANCEL_JUMP);
    }

    public static void payOrder(final Map<String, Object> map, final Activity activity, final String orderType) {
        final List<Map<String, Object>> goods;
        goods = (List<Map<String, Object>>) map.get("goods");
        final Intent intent = new Intent();
        final Bundle bundle = new Bundle();
        /**获取流水号回调方法*/
        PayManageImpl payManageImpl = new PayManageImpl(new IOuttradenoCallBack() {
            @Override
            public void data(JSONObject jsonObject) {
                ExitApplication.getInstance().addMainActivity(activity);
                try {
                    Map<String, Object> entity = JSONHelper.jsonToMap(jsonObject.get("entity").toString());
                    bundle.putString("outtradeno", entity.get("outtradeno").toString());
                    bundle.putString("points", entity.get("points").toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (StringUtil.isBlank(orderType)) {
                    bundle.putString("orderInfo", "商品订单");
                } else {
                    bundle.putString("orderInfo", orderType);
                }
                bundle.putString("totalPrice", Constant.RMB_FLAG + map.get("totalCost").toString());
                bundle.putString("totalCost", map.get("totalCost").toString());
                bundle.putString("orderID", map.get("orderID").toString());
                bundle.putString("status", "goods");
                bundle.putBoolean("orderList", true);/**支付成功后返回商品列表*/
                String orderType = String.valueOf(map.get("orderType"));
                bundle.putString("orderType", orderType);
                String module = getPaidTypeFromOrderType(orderType);
                if (!StringUtil.isBlank(module)) {
                    bundle.putString(PaymentModule.PAID_METHOD, module);
                }
                ArrayList<String> listProducts = new ArrayList<>();
                if (goods != null) {
                    for (int i = 0; i < goods.size(); i++) {
                        listProducts.add(goods.get(i).get("productID").toString());
                    }
                }
                bundle.putStringArrayList("productsID", listProducts);
                intent.putExtras(bundle);
                intent.setClass(activity, UsersPaidActivity.class);
                activity.startActivity(intent);
            }
        });
        payManageImpl.getOuttradenoFromServer(String.valueOf(map.get("orderID")), -1);
    }


    public static String timeStampToDate2(String timeMilis) {
        String time = "";
        if (timeMilis != null && !timeMilis.equals("")
                && !timeMilis.equals("null")) {
            time = TimeUtil.timeStampToDate(Long.parseLong(timeMilis),
                    "yyyy-MM-dd HH:mm:ss");
        }
        return time;
    }

    public static void setTextInfo(TextView textView, String format, String info) {
        if (StringUtil.isBlank(info)) {
            textView.setVisibility(View.GONE);
        } else {
            textView.setVisibility(View.VISIBLE);
            if (StringUtil.isBlank(format))
                textView.setText(info);
            else
                textView.setText(String.format(format, info));
        }
    }

    public static void setTextInfo(TextView textView, String info) {
        setTextInfo(textView, "", info);
    }

    /**
     * 判断配送方式是否是邮寄
     */
    public static boolean isPost(String shipType) {
        //TODO 应该写成常量
        if ("邮寄".equals(shipType)) {
            return true;
        }
        return false;
    }

    /**
     * 格式化时间
     *
     * @param time
     * @return
     */
    public static String formatDateTime(String time) {
        SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (time == null || "".equals(time)) {
            return "";
        }
        time = TimeUtil.timeStampToDate(Long.parseLong(time), "yyyy-MM-dd HH:mm");
        LogE.E(time);
        Date date;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
            return time;
        }

        Calendar inputCld = Calendar.getInstance();

        Calendar today = Calendar.getInstance();    //今天

        today.set(Calendar.YEAR, inputCld.get(Calendar.YEAR));
        today.set(Calendar.MONTH, inputCld.get(Calendar.MONTH));
        today.set(Calendar.DAY_OF_MONTH, inputCld.get(Calendar.DAY_OF_MONTH));
        //  Calendar.HOUR——12小时制的小时数 Calendar.HOUR_OF_DAY——24小时制的小时数
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);

        Calendar yesterday = Calendar.getInstance();    //昨天

        yesterday.set(Calendar.YEAR, inputCld.get(Calendar.YEAR));
        yesterday.set(Calendar.MONTH, inputCld.get(Calendar.MONTH));
        yesterday.set(Calendar.DAY_OF_MONTH, inputCld.get(Calendar.DAY_OF_MONTH) - 1);
        yesterday.set(Calendar.HOUR_OF_DAY, 0);
        yesterday.set(Calendar.MINUTE, 0);
        yesterday.set(Calendar.SECOND, 0);

        inputCld.setTime(date);

        if (inputCld.after(today)) {
            return "今天 ";
        } else if (inputCld.before(today) && inputCld.after(yesterday)) {
            return "昨天 ";
        } else {
            int index = time.indexOf(" ") + 1;
            return time.substring(0, index);
        }
    }

    public static boolean hasRead(String readFlag) {
        if ("0".equals(readFlag)) {
            return false;
        } else if ("1".equals(readFlag)) {
            return true;
        }
        return true;
    }

    /**
     * 展示和提交，这里只处理符合标准格式的金额（非数字、多小数点，无法处理，应该在输入时处理）1、整数补.00,2、一位小数补0，超过两位小数，截取
     */
    public static String handleMoney(Object moneys) {
        String money = String.valueOf(moneys);
        String moneyResult = "0.00";
        if (!StringUtil.isBlank(money)) {
            if (money.contains(".")) {
                int indexDot = money.indexOf(".");
                if (indexDot == 0) {
                    moneyResult = "0.00";
                } else if ((indexDot + 1) == money.length()) {//尾部一个点，加上00
                    moneyResult = money + "00";
                } else if ((money.length() - (indexDot + 1)) == 1) {//判断小数点后的位数
                    moneyResult = money + "0";
                } else if ((money.length() - (indexDot + 1)) > 2) {
                    moneyResult = money.substring(0, indexDot + 1 + 2);//开始 + 小数点 + 小数点后两位
                } else {
                    moneyResult = money;
                }
            } else {//整数补零
                moneyResult = money + ".00";
            }
        }
        return moneyResult;
    }
}
